/**
 * 日志模块数据操作文件
 */

const { query, pool } = require('./common');
const dayjs = require('dayjs');

/**
 * 添加日志
 * @param {*} message 
 * @param {*} type 
 */
const addLog = (message, type = 1) => query('INSERT INTO logs(message,type) VALUES (?,?)', [message, type]);

/**
 * 搜索日志
 * @param {*} model 搜索模型
 * @returns 
 */
const searchLogs = async model => {
    let { pageNo, pageSize, type, startDate, endDate } = model;
    const conn = await pool.getConnection();
    try {
        if (endDate) {
            const date = dayjs(endDate);
            endDate = date.add(1, 'day').format('YYYY-MM-DD');
        }
        const where = conn.format(`(? = 0 OR l.type = ?) AND date >= IFNULL(?,'2022-1-1') AND date < IFNULL(?,'2100-1-1')`, [type, type, startDate, endDate]);
        const [[list], [[count]]] = await Promise.all([
            conn.query(`SELECT id,message,date,type FROM(
                SELECT l.id,message,date,d.name type,ROW_NUMBER() OVER(ORDER BY l.id desc)num FROM logs l
                INNER JOIN dictionary d on l.type = d.id
                WHERE ${where}
                )t WHERE t.num > ? AND t.num <= ?`, [(pageNo - 1) * pageSize, pageNo * pageSize]),
            conn.query(`SELECT COUNT(1) count FROM logs l WHERE ${where}`)
        ]);
        return [list, count.count];
    } catch (error) {
        throw error;
    } finally {
        conn.release();
    }
}

module.exports = {
    addLog,
    searchLogs
}